package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "modules/Api/controllers"
    "class"
    "reflect"
    "strings"
)

type User struct {
    Id int32
    Name string
}

func RegisterRouter(r *gin.Engine) {
    ApiController.RegisterRouter(r)
    list := Class.X.GetList()
    for _, v := range list {
        tt := reflect.TypeOf(v)
        vv := reflect.ValueOf(v)
        temp := strings.Replace(tt.String(), "*", "", -1)
        data := strings.Split(temp, "Controller.")
        for i := 0; i < tt.NumMethod(); i++ {
            name := tt.Method(i).Name
            url := fmt.Sprintf("/%s/%s/%s", data[0], data[1], name)
            r.GET(url, func(c *gin.Context) {
                vv.MethodByName(name).Call([]reflect.Value{reflect.ValueOf(c)})
            })
        }
    }
}

func Sum(x, y int) int {
    return x + y
}

func main() {
    /*
        DebugMode
        ReleaseMode
        TestMode
        生产环境需要放开如下代码
        gin.SetMode(gin.ReleaseMode)
        开发环境可以设置为DebugMode，这样修改模板不用重新编译或者重启程序
    */
    r := gin.Default()
    r.Static("/static", "static")
    r.GET("/ping", func(c *gin.Context) {
        c.JSON(200, gin.H{"message": "pong"})
    })
    /*
        模板
    */
    r.LoadHTMLGlob("views/**/*")
    r.GET("/html", func(c *gin.Context) {
        data1 := User{1, "a1"}
        data2 := User{2, "a2"}
        data3 := User{3, "a3"}
        var dataList []User
        dataList = append(dataList, data2, data3)
        c.HTML(200, "user/index.html", gin.H{"title": "China", "data": data1, "dataList": dataList, "SumTest": Sum})
    })
    /*
        注册路由
    */
    RegisterRouter(r)
    /*
        得到控制器
        Demo := ApiController.NewDemo()
        Demo := ApiController.Demo{}
        Demo := &ApiController.Demo{}
    */
    Demo := &ApiController.Demo{}
    /*
        调用继承的方法(从Base来的)
    */
    pow := Demo.BaseTest(5)
    fmt.Println(pow)
    /*
        调用继承的方法(从ApiBase来的)
    */
    sum := Demo.ApiTest(10, 90)
    fmt.Println(sum)
    /*
        调用自己的方法
    */
    data := Demo.DemoTest("This is demo")
    fmt.Println(data)
    r.Run("0.0.0.0:10020")
}
